package com.ibpd.henuocms.web.controller.manage;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.propertyeditors.CustomBooleanEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ibpd.dao.impl.IBaseService;
import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.entity.baseEntity.IBaseEntity;
import com.ibpd.henuocms.assist.IbpdBooleanEditor;
import com.ibpd.henuocms.common.DateJsonValueProgressor;
import com.ibpd.henuocms.common.KVClass;
import com.ibpd.henuocms.common.FTPUtil;
import com.ibpd.henuocms.common.FileUtil;
import com.ibpd.henuocms.common.IbpdCommon;
import com.ibpd.henuocms.common.LongJsonValueProgressor;
import com.ibpd.henuocms.common.StaticPageEntity;
import com.ibpd.henuocms.common.StaticPageUtil;
import com.ibpd.henuocms.common.TxtUtil;
import com.ibpd.henuocms.entity.ContentEntity;
import com.ibpd.henuocms.entity.NodeAttrEntity;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.SubSiteEntity;
import com.ibpd.henuocms.service.content.ContentServiceImpl;
import com.ibpd.henuocms.service.content.IContentService;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.nodeAttr.INodeAttrService;
import com.ibpd.henuocms.service.nodeAttr.NodeAttrServiceImpl;
import com.ibpd.henuocms.service.subSite.ISubSiteService;
import com.ibpd.henuocms.service.subSite.SubSiteServiceImpl;
import com.ibpd.shopping.assist.InterfaceUtil;
import com.ibpd.shopping.entity.AccountEntity;
import com.sun.beans.editors.BooleanEditor;

public class BaseController {
	public static final String WEBPAGE_TYPE_VIEWER="viewer";
	public final String ERROR_PAGE="error";
	public String DEFAULT_RESULT_TEMPLATE="{\"status\":\"$status\",\"id\":\"$id\",\"msg\":\"$msg\"}";
	public static final String MSG_SUCCESS_STATUS="99";
	public static final String MSG_SUCCESS_ID="99";
	public static final String MSG_SUCCESS_MSG="执行成功";
	public static final String MSG_FAILUE_STATUS="-1";
	public static final String MSG_FAILUE_ID="-1";
	public static final String MSG_FAILUE_MSG="执行失败";
	public static final String MSG_PARAMERROR_STATUS="-2";
	public static final String MSG_PARAMERROR_MSG="参数错误";
	
	public static final String PAGE_TITLE="page_title";
	
	public static final String ERROR_MSG="error_msg";
	/**
	 * 根据web页面的type值确定是否是预览页面并返回虚拟目录（有的情况下），仅仅用作前台页面预览
	 * @param req
	 * @param type
	 * @return
	 */
	protected String getVisualPathByType(HttpServletRequest req,String type){
		if(StringUtils.isBlank(type)){
			return "/";
		}else if(type.toLowerCase().trim().equals(WEBPAGE_TYPE_VIEWER)){
			return req.getContextPath()+"/";
		}else{
			return "/";
		}
	}
	public String getJsonResult(String status,String id,String msg){
		return DEFAULT_RESULT_TEMPLATE.replace("$status",status).replace("$id", id).replace("$msg", msg);
	}
	public JsonConfig getDefaultJsonConfig(){ 
		JsonConfig conf=new JsonConfig();
		conf.registerJsonValueProcessor(Date.class, new DateJsonValueProgressor());
		conf.registerJsonValueProcessor(Long.class, new LongJsonValueProgressor());
		conf.registerJsonValueProcessor(Integer.class, new LongJsonValueProgressor());
		conf.registerJsonValueProcessor(Float.class, new LongJsonValueProgressor());
		conf.registerJsonValueProcessor(Double.class, new LongJsonValueProgressor());
		return conf;
	}
	public Object getValue(String val,String clazz){
		if(clazz.toLowerCase().equals(Boolean.TYPE.toString().toLowerCase())){
			if(val.toLowerCase().equals("true") || val.trim().equals("1")){
				return true;
			}else if(val.toLowerCase().equals("false") || val.trim().equals("0")){
				return false;
			}else{
				return Boolean.valueOf(val);				
			}
		}else if(clazz.toLowerCase().equals(Date.class.getSimpleName().toString().toLowerCase())){
			if(val.trim().length()==10){
				val=val+" 00:00:00";
			}
			if(val.trim().length()==13){
				val=val+":00:00";
			}
			if(val.trim().length()==16){
				val=val+":00";
			}
			SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
		    try {
		    	Date d = sdf.parse(val);
		    	return d;
		    } catch (ParseException e) {
		    	e.printStackTrace();
		    	return null;
		    }
		}else if(clazz.toLowerCase().equals(Integer.class.getSimpleName().toString().toLowerCase())){
			val=val.equals("")?"0":val;
			return Integer.parseInt(val);
		}else if(clazz.toLowerCase().equals(Long.class.getSimpleName().toString().toLowerCase())){
			val=val.equals("")?"0":val;
			return Long.parseLong(val);
		}else if(clazz.toLowerCase().equals(String.class.getSimpleName().toString().toLowerCase())){
			return val;
		}else if(clazz.toLowerCase().equals(Float.class.getSimpleName().toString().toLowerCase())){
			return Float.valueOf(val);
		}else if(clazz.toLowerCase().equals(Double.class.getSimpleName().toString().toLowerCase())){
			return Double.valueOf(val);
		}else{
			return val;
		}
	}

	public void printJsonData(HttpServletResponse response,String jsonString) throws IOException{
		response.getWriter().print(jsonString);
		response.getWriter().flush();

	}
	public HttpServletRequest getCurrentRequest(){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	public Object getService(Class clazz){
		return ServiceProxyFactory.getServiceProxy(clazz);
	}
	public void printDefaultSuccessMsg(HttpServletResponse resp) throws IOException{
		printMsg(resp,MSG_SUCCESS_STATUS,MSG_SUCCESS_ID,MSG_SUCCESS_MSG);
	}
	public void printDefaultFailueMsg(HttpServletResponse resp) throws IOException{
		printMsg(resp,MSG_FAILUE_STATUS,MSG_FAILUE_ID,MSG_FAILUE_MSG);
	}
	public void printParamErrorMsg(HttpServletResponse resp) throws IOException{
		printMsg(resp,MSG_PARAMERROR_STATUS,MSG_FAILUE_ID,MSG_PARAMERROR_MSG);
	}
	public void printMsg(HttpServletResponse response,String status,String id,String msg) throws IOException{
		response.getWriter().print(getJsonResult(status,id,msg));
		response.getWriter().flush();
	}
	public void getList(HttpServletRequest req,IBaseService service,HttpServletResponse resp,String order,Integer page,Integer rows,String sort,String queryData){
		getList(req,service,resp,order,page,rows,sort,queryData,false);
	}
	public void getList(HttpServletRequest req,IBaseService service,HttpServletResponse resp,String order,Integer page,Integer rows,String sort,String queryData,Boolean useDefaultConfig){
		order=(order==null)?"asc":order;
		sort=(sort==null)?"id":sort;
		page=(page==null)?1:page;  
		rows=(rows==null)?10:rows;
		queryData=(queryData==null || queryData.equals(""))?null:queryData;
		String whereStr="";
		if(queryData!=null){
			whereStr=" where "+queryData;
		} 
		List etList=service.getList("from "+service.getTableName()+whereStr,null,sort+" "+order,  rows,rows*(page-1));
		Long rowCount=service.getRowCount(whereStr,null);
		try {
		    JSONArray jsonArray = null;//JSONArray.fromObject( etList.toArray() );
		    if(useDefaultConfig){
		    	jsonArray = JSONArray.fromObject( etList.toArray() ,this.getDefaultJsonConfig());
		    }else{
		    	jsonArray = JSONArray.fromObject( etList.toArray() );
		    }
			PrintWriter out = resp.getWriter();
			 out.print("{\"total\":"+rowCount.toString()+",\"rows\":"+jsonArray+"}");
			 out.flush();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void getList(HttpServletRequest req,IBaseService service,HttpServletResponse resp,String order,Integer page,Integer rows,String sort,String queryData,String... clearFields) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
		order=(order==null)?"asc":order;
		sort=(sort==null)?"id":sort;
		page=(page==null)?1:page;  
		rows=(rows==null)?10:rows;
		queryData=(queryData==null || queryData.equals(""))?null:queryData;
		String whereStr="";
		if(queryData!=null){
			whereStr=" where "+queryData;
		} 
		List etList=service.getList("from "+service.getTableName()+whereStr,null,sort+" "+order,  rows,rows*(page-1));
		processList(etList,clearFields);
		Long rowCount=service.getRowCount(whereStr,null);
		sendJsonByList(resp,etList,rowCount);
	}

	protected void processList(List lst,String[] clearFields) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
		if(clearFields==null || clearFields.length==0)
			return;
		//
		if(lst==null)
			return;
		if(lst.size()==0)
			return;
		//
		for(Object obj:lst){
			for(String field:clearFields){
				String setMetName="set"+field.substring(0,1).toUpperCase()+field.substring(1);
				String getMetName="get"+field.substring(0,1).toUpperCase()+field.substring(1);
				Method[] mhds=obj.getClass().getMethods();
				for(Method mt:mhds){
					if(mt.getName().equals(setMetName)){
						Method getmet=obj.getClass().getMethod(getMetName, null);
						mt.invoke(obj, getValue("0",getmet.getReturnType().getSimpleName()));
						break;
					}
				}
			}
		}
	}

	public enum MakeType{
		站点,
		栏目,
		内容,
		其他
	}
	public void makeStaticPage(MakeType makeType,IBaseEntity entity,Integer pageSize,Integer pageIndex){
		Long id=-1L;
		if(entity instanceof SubSiteEntity){
			SubSiteEntity site=(SubSiteEntity)entity;
			id=site.getId();
		}else if(entity instanceof NodeEntity){
			NodeEntity node=(NodeEntity)entity;
			id=node.getId();
		}else if(entity instanceof ContentEntity){
			ContentEntity cnt=(ContentEntity)entity;
			id=cnt.getId();
		}
		makeStaticPage(makeType,id,pageSize,pageIndex);
	}
	public void makeStaticPage(MakeType makeType,Long id,Integer pageSize,Integer pageIndex){
		String url="";
		IBaseEntity entity=null;
		String siteDirName="";
		SubSiteEntity baseSite=null;
//		url=this.getCurrentRequest().getScheme() + "://"+ this.getCurrentRequest().getServerName() + ":" + this.getCurrentRequest().getServerPort()+ this.getCurrentRequest().getContextPath() + "/";
		url=this.getCurrentRequest().getScheme() + "://localhost:" + this.getCurrentRequest().getServerPort()+ this.getCurrentRequest().getContextPath() + "/";
		if(id==null)
			return;
		ISubSiteService siteServ=(ISubSiteService) getService(SubSiteServiceImpl.class);
		SubSiteEntity site=null;
		switch(makeType){
		case 站点:
			site=siteServ.getEntityById(id);
			entity=site;
			if(site==null){
				return;
			}
			baseSite=site;
			siteDirName=site.getDirectory();
			url=url+"Web/SubSite/index.do?siteId="+id;
			break;
		case 栏目:
			INodeAttrService nodeServ=(INodeAttrService) getService(NodeAttrServiceImpl.class);
			NodeAttrEntity attr=nodeServ.getNodeAttr(id);
			INodeService ns=(INodeService) getService(NodeServiceImpl.class);
			NodeEntity n=ns.getEntityById(id);
			entity=attr;
			if(attr==null && n!=null){
				return;
			}
			site=siteServ.getEntityById(n.getSubSiteId());
			
			if(site!=null){
				siteDirName=site.getDirectory();
				baseSite=site;
			}
			url=url+"Web/Node/index.do?nodeId="+id;
			break;
		case 内容: 
			IContentService contentServ=(IContentService) getService(ContentServiceImpl.class);
			ContentEntity ce=contentServ.getEntityById(id);
			entity=ce;
			site=siteServ.getEntityById(ce.getSubSiteId());
			if(site!=null){
				siteDirName=site.getDirectory();
				baseSite=site;
			}
			if(ce==null)
				return;
			url=url+"Web/Content/index.do?contentId="+id;
			break;
		case 其他:
			break;
		}
		String flName=getFileName(makeType,entity);
		//这里应该考虑一下生成策略，不要每次都生成，但没想到很好的解决办法，先这样吧，如果按照栏目生成的话，内容数量还不至于太大
		//总之这样肯定不好
		//有一个办法，就是对照内容 在数据库中的最后保存日期，如果是当前日期则生成，否则不做处理,或者针对md5等方式的比较
		StaticPageEntity sp=new StaticPageEntity();
		sp.setUrl(url);
		sp.setUrlParams(null);
		sp.setFileName(flName); 
		WriteHtmlFileThread w=new WriteHtmlFileThread(baseSite,sp,siteDirName);
		w.start();
	}
	protected void uploadToServer(SubSiteEntity site,String flName){
		if(!StringUtils.isBlank(flName)){
			File f=new File(flName); 
			if(f.exists() && f.isFile() && f.canRead()){
				String fl=f.getParentFile().getAbsolutePath().replace(FileUtil.getWebRootDirPath()+"sites","");
				UploadToServerThread th=new UploadToServerThread(site.getFtpAddress(),site.getFtpPassword(),site.getFtpUserName(),site.getFtpPassword(),"/",fl.substring(fl.indexOf(File.separator),fl.length()),flName);
				th.start();
			}
		}
	}
	/**
	 * 更新同步本地和ftp服务器端template和uploadFiles文件夹的内容，文件越多速度越慢
	 */
	protected void updateBinaryFilesToServer(SubSiteEntity site){ 
		String tempPath=FileUtil.getWebRootDirPath()+File.separator+"template";
		String uploadPath=FileUtil.getWebRootDirPath()+File.separator+"uploadFiles";
		List<File> fl=new ArrayList<File>();  
		fl=getAllFiles(new File(tempPath),fl);
		for(File f:fl){
			File df=f.getParentFile();
			String serverPath="/template/"+df.getAbsolutePath().replace(File.separator, "/").split("/template/")[1]+"/";
			System.out.println("server path:"+serverPath);
			UploadToServerThread th=new UploadToServerThread(site.getFtpAddress(),site.getFtpPassword(),site.getFtpUserName(),site.getFtpPassword(),"/",serverPath,f.getAbsolutePath());
			th.start();  
		}
		fl=new ArrayList<File>(); 
		fl=getAllFiles(new File(uploadPath),fl);
		for(File f:fl){
			File df=f.getParentFile();
			String serverPath="/uploadFiles/"+df.getAbsolutePath().replace(File.separator, "/").split("/uploadFiles/")[1]+"/";
			System.out.println("server path:"+serverPath);
			UploadToServerThread th=new UploadToServerThread(site.getFtpAddress(),site.getFtpPassword(),site.getFtpUserName(),site.getFtpPassword(),"/",serverPath,f.getAbsolutePath());
			th.start(); 
		}
	}
	private List<File> getAllFiles(File path,List<File> flList){ 
		if(path.exists()){
			if(path.isFile()){
				flList.add(path);
				return flList;
			}else{
				File[] fl=path.listFiles();
				for(File f:fl){
					flList=getAllFiles(f,flList);
				}
				return flList;
			}
		}else{
			return flList;
		}
	}
	private String getFileName(MakeType makeType,IBaseEntity entity){
		if(entity==null)
			return null;
		String dir="";
		String path=this.getCurrentRequest().getRealPath("/")+File.separator+"sites";
		switch(makeType){
		case 站点:
			SubSiteEntity site=(SubSiteEntity) entity;
			path=path+File.separator+site.getDirectory();
			FileUtil.makeDir(path);
			dir=path+File.separator+"index.html";
			break;
		case 栏目:
			NodeAttrEntity attr=(NodeAttrEntity) entity;
			Long nodeId=attr.getNodeId();
			INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
			NodeEntity node=nodeServ.getEntityById(nodeId);
			if(node==null)
				return null;
			ISubSiteService siteServ=(ISubSiteService) getService(SubSiteServiceImpl.class);
			SubSiteEntity s=siteServ.getEntityById(node.getSubSiteId());
			String idpath=node.getNodeIdPath();
			idpath=idpath.split(nodeId.toString())[0];
			String[] ids=idpath.split(NodeEntity.NODEIDPATH_SPLIT);
			INodeAttrService attrServ=(INodeAttrService) getService(NodeAttrServiceImpl.class);
			String npath="";
			for(String  id:ids){
				if(StringUtil.isNumeric(id)){
					NodeAttrEntity na=attrServ.getNodeAttr(Long.parseLong(id));	
					npath+=na.getDirectory()+File.separator;
				}
			}
			path=path+File.separator+s.getDirectory()+File.separator+npath+attr.getDirectory();
			FileUtil.makeDir(path);
			dir=path+File.separator+"index.html";
			break;
		case 内容:
			ContentEntity ce=(ContentEntity) entity;
			INodeAttrService ns=(INodeAttrService) getService(NodeAttrServiceImpl.class);
			NodeAttrEntity na=ns.getNodeAttr(ce.getNodeId());
			String nodePath=getFileName(MakeType.栏目,na);
			nodePath=nodePath.substring(0,nodePath.lastIndexOf(File.separator));
			nodePath=nodePath+File.separator+"cnt-"+ce.getId()+".html";
			dir=nodePath;
			break;
		case 其他:
			break;
		}
		return dir;
	}
	public void swap(Object formAcc,Object dbAcc) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		Method[] methods=formAcc.getClass().getMethods();
		for(Method getMethod:methods){
			String getMethodName=getMethod.getName();
			if(getMethodName.substring(0,3).equals("get") && !getMethodName.equals("getClass")){
				String setMethodName="set"+getMethodName.substring(3);
				Method setMethod=dbAcc.getClass().getMethod(setMethodName, getMethod.getReturnType());
				if(setMethod!=null){
					setMethod.invoke(dbAcc, getMethod.invoke(formAcc, null));
				}
			}
		}
	}

	protected Object getEntityFieldValue(IBaseEntity entity,String field) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(entity==null)
			return null;
		if(field==null)
			return null;
		//为了避免多实体的情况下，field为entity.field这种类型，防止无法正确取值的问题，特别在这里处理一下，且不影响其他地方
		String[] flds=field.split("\\.");
		if(flds.length>1){
			field=flds[flds.length-1];
		}
		String getMethodName="get"+field.substring(0,1).toUpperCase()+field.substring(1);
		Method[] mts=entity.getClass().getMethods();
		for(Method mt:mts){
			if(mt.getName().equals(getMethodName)){
				return mt.invoke(entity, null);
			}
		}
		return null;
	}
	protected LinkedHashMap<String,KVClass> getHtmlString(IBaseEntity entity,String propKey) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		String htmlFields=IbpdCommon.getInterface().getEntityHtmlFields(propKey);
		if(htmlFields==null){
			return null;
		}
		LinkedHashMap<String,KVClass> map=new LinkedHashMap<String,KVClass>();
		String[] fields=htmlFields.split(";");//name:名称:text:;code:编码:text:;order:排序:text:;showInNav:导航中显示:select:显示-y,隐藏-n:null
		String un="";
		for(String field:fields){
			String[] f=field.split(":");
			if(f.length==7){
				String fieldName=f[0];
				String displayName=f[1];
				String type=f[2];
				String defaultValue=f[3].equals("null")?"":f[3];
				String ftype=f[4];
				String required=f[5];
				String validType=f[6];
				required=(required.equals("") || required.trim().toLowerCase().equals("null") || required.trim().toLowerCase().equals("false"))?"":required;
				validType=(validType.equals("") || validType.trim().toLowerCase().equals("null")?"":validType);
				KVClass ass=new KVClass();
				ass.setK(ftype);
				ass.setV(getHtmlString(fieldName,displayName,type,defaultValue,ftype,required,validType,entity));
				map.put(displayName, ass);
			}else{
				un+=field+"\r\n";
			}
		}
		try {
			TxtUtil.writeTxtFile(un, new File("d:\\un.txt"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	private String getHtmlString(String fieldName,String displayName,String type,String defaultValue,String ftype,String required,String validType,IBaseEntity entity) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		String dataoptions="";
		if(!StringUtil.isBlank(required)){
			if(!StringUtil.isBlank(validType)){
				dataoptions="data-options=\"required:true,validType:'"+validType+"'\"";
			}else{
				dataoptions="data-options=\"required:true\"";
			}
		}else{
			if(StringUtil.isBlank(validType)){
				dataoptions="data-options=\"validType:'"+validType+"'\"";
			}else{
				dataoptions="";
			}
		}
		String classString="";
		if(!dataoptions.equals("")){
			classString="class=\"easyui-validatebox\"";
		}
		if(type.toLowerCase().trim().equals("text")){
			Object value=getEntityFieldValue(entity, fieldName);
			if(value==null)
				value=defaultValue;
			return "<input "+classString+" "+dataoptions+" type=\"text\" mthod=\"smt\" name=\""+fieldName+"\" value=\""+value+"\"/>\n";
		}else if(type.toLowerCase().trim().equals("date")){
			Object value=getEntityFieldValue(entity, fieldName);
			if(value==null)
				value=defaultValue;
			return "<input "+classString+" "+dataoptions+" type=\"text\" mthod=\"smt\" name=\""+fieldName+"\" value=\""+value+"\"smt=\"dateSelecter\"/>\n";
		}else if(type.toLowerCase().trim().equals("hidden")){
			Object value=getEntityFieldValue(entity, fieldName);
			if(value==null)
				value=defaultValue;
			return value+"<input type=\"hidden\" mthod=\"smt\" name=\""+fieldName+"\" value=\""+value+"\"/>\n";
		}else if(type.toLowerCase().trim().equals("file")){
			Object value=getEntityFieldValue(entity, fieldName);
			if(value==null)
				value=defaultValue;
			return "<input "+classString+" "+dataoptions+" type=\"text\" mthod=\"smt\" name=\""+fieldName+"\" value=\""+value+"\"/><input type=\"button\" smt=\"fileSelecter\" name=\""+fieldName+"_fileSelecter\"/>\n";
		}else if(type.toLowerCase().trim().equals("label")){
			Object value=getEntityFieldValue(entity, fieldName);
			if(value==null)
				value=defaultValue;
			return "<label>"+value+"</label><input type=\"hidden\" mthod=\"smt\" name=\""+fieldName+"\" value=\""+value+"\"/>\n";
		}else if(type.toLowerCase().trim().equals("area")){
			Object value=getEntityFieldValue(entity, fieldName);
			if(value==null)
				value=defaultValue;
			return "<textarea "+classString+" "+dataoptions+" mthod=\"smt\" name=\""+fieldName+"\">"+value+"</textarea>\n";
		}else if(type.toLowerCase().trim().equals("select")){
			Object value=getEntityFieldValue(entity, fieldName);
			if(value==null)
				value=defaultValue;
			if(defaultValue==null && StringUtil.isBlank(defaultValue))
				defaultValue="";
			String selectString="<select mthod=\"smt\" name=\""+fieldName+"\" value=\""+value+"\">\n";
			String[] def=defaultValue.split(",");
			for(String d:def){
				String[] kv=d.split("-");
				selectString+="\t<option value=\""+kv[1]+"\""+(equal(kv[1],value)?"selected":"")+">"+kv[0]+"</option>\n";
			}
			selectString+="</select>\n";
			return selectString;
		}else{
			return getHtmlString(fieldName, displayName,"text", defaultValue,ftype,required,validType,entity);
		}
//		return null;
	}
	private Boolean equal(Object a,Object b){
		//这里只做基本数据类型的对比
		return a.toString().equals(b.toString());
	}
	protected void sendJsonByList(HttpServletResponse resp,List entityList,Long rowCount){
//		List<Hashtable<String,String>> lst=convertToHashTable(entityList);
		try {
		    JSONArray jsonArray = JSONArray.fromObject( entityList.toArray(), getDefaultJsonConfig());
		    
			PrintWriter out = resp.getWriter();
			 out.print("{\"total\":"+rowCount.toString()+",\"rows\":"+jsonArray+"}");
			 out.flush();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	protected List<Hashtable<String,String>> convertToHashTable(List lst){
		List<Hashtable<String,String>> rtn=new ArrayList<Hashtable<String,String>>();
		if(lst==null)
			return rtn;
		if(lst.size()==0)
			return new ArrayList<Hashtable<String,String>>();
		for(Object be:lst){
			Hashtable<String,String> behash=new Hashtable<String,String>();
			List<Method> enabMhdList=getMethods(be);
			for(Method mhd:enabMhdList){
				try {
					String mhdName=getFieldName(be,mhd);
					Object val=mhd.invoke(be, new Object[]{});
					behash.put(mhdName, (val!=null)?val.toString():"");
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			rtn.add(behash);
		}
		return rtn;
	}
	
	private List<Method> getMethods(Object be){
		Method[] mhds=be.getClass().getMethods();
		List<Method> enabMhdList=new ArrayList<Method>();
		try{
		for(Method mhd:mhds){
			String mhdName=getFieldName(be,mhd);
			if(mhdName==null)
				continue;
			enabMhdList.add(mhd);
		}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return enabMhdList;
	}
	private String getFieldName(Object be,Method mhd) throws NoSuchMethodException, SecurityException{
		if(mhd==null)
			return null;
		String methodName=mhd.getName();
		if(methodName.startsWith("get") && !methodName.equals("getClass")){
			String  fieldName=methodName.replace("get", "");
			if(StringUtils.isBlank(fieldName))
				return null;
			fieldName=fieldName.substring(0,1).toLowerCase()+fieldName.substring(1);
			String setMhdName=methodName.replace("get", "set");
			Method setMhd=getMethod(be,setMhdName);
			if(setMhd!=null)
				return fieldName;
		}
		return null;
	}
	protected Method getMethod(Object obj,String mtName){

		Method[] mts=obj.getClass().getMethods();
		for(Method mt:mts){
			if(mt.getName().equals(mtName)){
				return mt;
			}
		}
		return null;
	}

	public Object getBeanFromSpringDefinedBeans(String beanName){
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getCurrentRequest().getSession().getServletContext());   
		return wac.getBean(beanName);
	}
	protected Long getCurrentLoginedUserId(HttpServletRequest req){
		AccountEntity ae=InterfaceUtil.getLoginedAccountInfo(req);
		if(ae==null){
			String userId=req.getParameter("userId");
			if(StringUtils.isBlank(userId)){
				return -1L;
			}else{
				return Long.valueOf(userId);
			}
		}else{
			return ae.getId();
		}
	}
	/**
	 * 将单个文件上传到FTP服务器端 
	 * @param filePath
	 * @param serverPath
	 */
	public void uploadBinaryFileToServer(SubSiteEntity site,String filePath,String serverPath){
		if(site==null){
			return;
		}
		UploadToServerThread th=new UploadToServerThread(site.getFtpAddress(),site.getFtpPort(),site.getFtpUserName(),site.getFtpPassword(),"/",serverPath,filePath);
		th.start(); 
	}
	@InitBinder  
    protected void initBinder(WebDataBinder binder) {  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));  
        binder.registerCustomEditor(Boolean.class, new IbpdBooleanEditor());
    } 
}
class UploadToServerThread extends Thread{
	public String ftpAddress="";
	public String port="";
	public String userName="";
	public String password="";
	public String workDir="";
	public String flPath="";
	public String flName="";
	public UploadToServerThread(String ftpAddress,String port,String userName,String password,String workDir,String path,String flName){
		this.flPath=path;
		this.flName=flName;
		this.ftpAddress=ftpAddress;
		this.port=port;
		this.userName=userName;
		this.password=password;
		this.workDir=workDir;
	}
	@Override
	public void run() {
		flPath=flPath.replace(File.separator, "/");
			String workDir=flPath;
			System.out.println("workDir:"+workDir);
			try {
				FTPUtil.getNewInterface(ftpAddress,port,userName,password,workDir).uploadFiles(workDir, flName);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		super.run();
	}
}
class WriteHtmlFileThread extends Thread{
	private StaticPageEntity sp=null;
	private String siteDirName="";
	private SubSiteEntity site=null;
	public WriteHtmlFileThread(SubSiteEntity site,StaticPageEntity spe,String siteDirName){
		this.sp=spe; 
		this.siteDirName=siteDirName;
		this.site=site;
	}
	@Override
	public void run() {
		StaticPageUtil.writeHtmlToHtmlFile(sp);
		String fl=new File(sp.getFileName()).getParentFile().getAbsolutePath().replace(FileUtil.getWebRootDirPath()+File.separator+"sites"+File.separator+siteDirName,"");
		(new BaseController()).uploadBinaryFileToServer(site,sp.getFileName(),fl);
		super.run();
	}
	
}

